package com.cy.law.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * json 基础工具类
 */
@Slf4j
public class JSONUtil {
    private static ObjectMapper objectMapper;

    private static ObjectMapper getObjectMapper() {
        if (null == objectMapper) {
            objectMapper = new ObjectMapper();
        }
        return objectMapper;
    }

    public static String toString(Object obj) {
        try {
            return getObjectMapper().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T toObject(String json, Class clzz) {
        try {
            return (T) getObjectMapper().readValue(json, clzz);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

}